<?php

$coords_fpath = "coords.txt";
$width = 20;
$height = 20;

if (!isset($map_glob)) { $map_glob = mRead(); }


	 
switch ($_POST['t']) {
	case 0:
		$map = mRead();	
		echo json_encode($map);
		break;
	case 1:
		$str = playerCoordsGet();
		$c = explode(",",$str);
		$x1 = (int)$c[0];
		$y1 = (int)$c[1];
		
		switch ($_POST['m']){
			case 0:
				break;
			case 1:
				if ($map_glob[$x1-1][$y1-2] < 1){ $y1--; }
				break;
			case 2:
				if ($map_glob[$x1][$y1-2] < 1){
					$x1++;
					$y1--;
				}
				break;
			case 3:
				$x1++;
				break;
			case 4:
				$x1++;
				$y1++;
				break;
			case 5:
				$y1++;
				break;
			case 6:
				$y1++;
				$x1--;
				break;
			case 7:
				$x1--;
				break;
			case 8:
				$x1--;
				$y1--;
				break;				
		}
		
		$new = $x1.",".$y1;
		echo $new;
		playerCoordsPut($x1,$y1);
		break;
	case 2:
		echo playerCoordsGet();
		break;
}

function playerCoordsPut($x,$y){
	global $coords_fpath;
	$put = $x.",".$y;
	file_put_contents($coords_fpath, $put);
}

function playerCoordsGet(){
	global $coords_fpath;
	$cnt = file_get_contents($coords_fpath);
	$c = explode(",",$cnt);
	
	return $c[0].",".$c[1];
}

function checkCollision($x, $y, $map_glob){
	
	if ($map_glob[$x-1][$y-1] == 0) { return true; }
	return false;
}

function mRead(){
	$res = fopen("map.txt", "r") or die("Error reading file");
	$map = array();
	$i = 0;
	
	while(!feof($res)){
		$line = fgets($res);
		$line = trim($line, "\r\n.");
		
		$larr = explode(",", $line);
		$map[$i] = array();
		$cnt = sizeof($larr);
		
		for ($j=0; $j<$cnt; $j++){
			$map[$i][$j] = (int)$larr[$j];
		}
		$i++;
	}
	fclose($res);
	
	return $map;
}

?>
